#include <iostream>
#include <websocketpp/server.hpp>
#include <websocketpp/config/asio_no_tls.hpp>

using asio_wssvr_t = websocketpp::server<websocketpp::config::asio>;

void on_http_request(asio_wssvr_t *svr, websocketpp::connection_hdl hdl) {
    /**
     * 1.了解如何获取http请求内容, 包括以下内容：
     *  a. 获取连接 => 请求内容是保存在连接当中的
     *  b. 请求方法
     *  c. 请求路径
     *  d. 请求头部
     *  e. 请求正文
     */
    asio_wssvr_t::connection_ptr conn = svr->get_con_from_hdl(hdl);
    websocketpp::http::parser::request request = conn->get_request();
    std::cout << "http method: " << request.get_method() << std::endl;
    std::cout << "http uri: " << request.get_uri() << std::endl;
    std::cout << "http version: " << request.get_version() << std::endl;
    auto headers = request.get_headers();
    for (const auto& header : headers) {
        std::cout << "http header: " << header.first << ":" << header.second << std::endl;
    }
    std::cout << "http body: " << request.get_body() << std::endl;
    
    /* 2.给客户端返回"hello world"前端页面 */
    std::string body = "<html><body><h1>Hello World</h1></body></html>";
    conn->set_body(body);
    conn->append_header("Content-Type", "text/html");
    conn->set_status(websocketpp::http::status_code::ok);
}
void on_connection_open(asio_wssvr_t *svr, websocketpp::connection_hdl hdl) {
    std::cout << "connection open\n";
}
void on_connection_close(asio_wssvr_t *svr, websocketpp::connection_hdl hdl) {
    std::cout << "connection close\n";
}
void on_message_received(asio_wssvr_t *svr, websocketpp::connection_hdl hdl, asio_wssvr_t::message_ptr msg) {
    std::cout << "receive message from websocket connection\n";
    std::cout << "message contect is: " << msg->get_payload() << std::endl << std::endl;

}
int main() {
    asio_wssvr_t server;                                            /* 1.实例化server对象 */
    server.set_access_channels(websocketpp::log::alevel::none);     /* 2.设置日志等级为禁止打印所有日志信息 */
    server.init_asio();                                             /* 3.初始化 asio 调度器 */

    /* 4.设置业务处理回调 */
    server.set_http_handler(std::bind(&on_http_request, &server, std::placeholders::_1));
    server.set_open_handler(std::bind(&on_connection_open, &server, std::placeholders::_1));
    server.set_close_handler(std::bind(&on_connection_close, &server, std::placeholders::_1));
    server.set_message_handler(std::bind(&on_message_received, &server, std::placeholders::_1, std::placeholders::_2));

    server.listen(8888);        /* 5.设置服务器监听端口 */
    server.start_accept();      /* 6.开始接收连接 */
    server.run();               /* 7.运行服务器 */

    return 0;
}